package com.lsu.car.controller;

import com.lsu.car.constants.Constants;
import com.lsu.car.constants.HttpStatus;
import com.lsu.car.domain.LoginInfo;
import com.lsu.car.dto.LoginBodyDto;
import com.lsu.car.service.LoginInfoService;
import com.lsu.car.vo.ActiverUser;
import com.lsu.car.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private LoginInfoService loginInfoService;

    @PostMapping("login/doLogin")
    public AjaxResult login(@RequestBody @Validated LoginBodyDto loginBodyDto, HttpServletRequest httpServletRequest){
        AjaxResult ajaxResult = AjaxResult.success();
//        通过传来参数获取用户名和密码
        String username = loginBodyDto.getUsername();
        String password = loginBodyDto.getPassword();

//        通过传来得用户名和密码构造token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        /**获取登录的主体*/
        Subject subject = SecurityUtils.getSubject();
//        封装login_info对象
        try{
            subject.login(token);
            Serializable webToken = subject.getSession().getId();
            ajaxResult.put(Constants.TOKEN,webToken);
        }catch (AuthenticationException e){
            log.error("用户名或密码不正确");
            ajaxResult = AjaxResult.error(HttpStatus.ERROR, "用户名或密码不正确");
        }
        return ajaxResult;
    }

//    登录后获取用户信息
    @GetMapping
    public AjaxResult getInfo(){
//        获取登录的主体
        Subject subject = SecurityUtils.getSubject();
//        获取登录对象
        ActiverUser activerUser = (ActiverUser)subject.getPrincipal();
        AjaxResult ajaxResult = AjaxResult.success();
//        获取用户名
        ajaxResult.put("username",activerUser.getUser().getUserName());
//        ajaxResult.put("username",activerUser.getUser().getUserName());
        return ajaxResult;
    }


}
